package com.qar.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qar.domain.User;
import com.qar.exp.BusinessException;
import com.qar.resp.ResultData;
import com.qar.resp.ReturnCodeEnum;
import com.qar.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserCrotroller {
    @Autowired
    private UserService userService;


    //根据id查询信息
    @GetMapping("/get/{id}")
    public ResultData<User> getUserById(@PathVariable("id") Integer id) {
        return ResultData.success(userService.getById(id));
    }

    //添加用户数据
    @PostMapping("/add")
    public ResultData<Boolean> addUser(@RequestBody User user) {

        //一次添加多个数据
        for (int i = 0; i < 20; i++) {
            User u=new User();
            u.setUsername(user.getUsername()+IdUtil.simpleUUID().substring(0,4));
            u.setPassword("12346");
            u.setSex(1);
            userService.save(u);
        }
/*
        一次添加一个数据
        userService.save(user);*/

        return ResultData.success(Boolean.TRUE);
    }

    //删除用户数据
    @DeleteMapping("/del/{id}")
    public ResultData<Boolean> delUser(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return ResultData.success(Boolean.TRUE);
    }

    //修改用户数据
    @PutMapping(value = "/update")
    public ResultData<Boolean> update(@RequestBody User user)
    {

        User oldUser = userService.getBaseMapper().selectById(user.getId());

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper
                .set(User::getUsername,user.getUsername())
                .set(User::getPassword,user.getPassword())
                .set(User::getSex,user.getSex())
                .set(User::getVersion,oldUser.getVersion()+1)
                .eq(User::getId,user.getId())
                .eq(User::getVersion,oldUser.getVersion());

        return ResultData.success(userService.update(updateWrapper));
    }

    //并发修改
    @PutMapping(value = "/user/updateConcurrent")
    public ResultData<Boolean> updateConcurrent(@RequestBody User user)
    {
        User oldUser1 = userService.getBaseMapper().selectById(user.getId());
        User oldUser2 = userService.getBaseMapper().selectById(user.getId());

        //修改密码
        oldUser1.setPassword("xxx");
        userService.getBaseMapper().updateById(oldUser1);

        oldUser2.setPassword("kkk");
        int count = userService.getBaseMapper().updateById(oldUser2);

        if(count == 0)
        {
            System.out.println("oldUser2=====update fail");
            return ResultData.success(Boolean.FALSE);
        }else{
            System.out.println("oldUser2=====update success");
            return ResultData.success(Boolean.TRUE);
        }
    }

    //异常处理
    @GetMapping(value = "/user/get/{id}")
    public ResultData<User> getById(@PathVariable("id") Integer id)
    {
        if(id == -4) throw new RuntimeException("id不能为负数");

        if (id < 0) {
            throw new BusinessException(ReturnCodeEnum.REQPARAM_NEGATIVE.getCode(), ReturnCodeEnum.REQPARAM_NEGATIVE.getMessage());
        }
        return ResultData.success(userService.getById(id));
    }

    //查询所有用户数据
    @GetMapping(value = "/user/list")
    public ResultData<List<User>> list()
    {
        List<User> list = userService.list();

        return ResultData.success(list);
    }

    //根据用户名查询用户数据
    @GetMapping(value = "/user/get")
    public ResultData<User> getByUseName(@RequestParam("username") String username)
    {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);

        return ResultData.success(userService.getOne(queryWrapper));
    }

    /**
     *  MybatisPlus原生分页插件IPage增强
     */
    @GetMapping("/user/selectPage")
    public List<User> selectPage(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize)
    {
        IPage<User> page = new Page(pageNum,pageSize); //import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
        return userService.page(page).getRecords();
    }

    //故意报错演示trycatch

    @RequestMapping(value = "/pay/error",method = RequestMethod.GET)
    public ResultData<Integer> getPayError()
    {
        Integer i = Integer.valueOf(200);
        try
        {
            System.out.println("--------come here");
            int data = 10/0;
        }catch (Exception e){
            e.printStackTrace();
            return ResultData.fail(ReturnCodeEnum.RC500.getCode(),e.getMessage());
        }
        return ResultData.success(i);
    }







}
